﻿using Castle.DynamicProxy;
using EMC.VISITOR.Core.Option;
using Microsoft.AspNetCore.Routing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EMC.VISITOR.Core
{
    public class CustomInterceptor : ActionFilterAttribute
    {
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var filter = App.GetOptions<ControllerActionFilterOptions>();
            bool goVis = false;
            if (filter.GlobalEnabled)
            {
                var controllerName = context.HttpContext.GetRouteValue("controller");
                var actionName = context.HttpContext.GetRouteValue("action");


                if (filter.CanUseControllers != null && filter.CanUseControllers.Length > 0)
                {
                    if (filter.CanUseControllers.Select(r => r.ToLower()).Contains(controllerName.ToString().ToLower()))
                        goVis = true;
                    else
                        goVis = false;
                }

                if (filter.NoUseControllers != null && filter.NoUseControllers.Length > 0)
                {
                    if (filter.NoUseControllers.Select(r => r.ToLower()).Contains(controllerName.ToString().ToLower()))
                        goVis = false;
                }

                if (filter.CanUseControllers == null && filter.NoUseControllers == null && filter.CanUseActions == null && filter.NoUseActions == null)
                    goVis = true;
            }
            else
                goVis = true;

            if (goVis == false)
                context.Result = new ObjectResult(CustomeResult.Fail<string>("无权访问"));
            else
                await next();
        }
    }
}
